import socket
import traceback
import re
get_str = """GET /%s HTTP/1.1
Host:%s
Connection:keep-alive

"""


def socket_client(url, ip, port=80, param=''):
    send_str = get_str % (param, url)
    print(send_str)
    client = socket.socket()
    try:
        client.connect((ip, port))
        send_bytes = send_str.encode(encoding='utf-8')
        client.send(send_bytes)
        r = client.recv(4096)
        resp = ''
        while r:
            resp += r.decode()
            r = client.recv(4096)
        client.close()
        return resp
    except Exception as e:
        client.close()
        traceback.print_exc()


def result_format(result: str):
    """

    :param result:
    :return:
    """

    r_content = re.finditer('<.*>', result)
    r_content_list = list(r_content)
    content, code, msg = '', '', ''
    header = {}
    if len(r_content_list) > 0:
        content = r_content_list[0].group()
    r_code = re.finditer('HTTP/1.1 ([2|3|4|5][0-9]{2}) (.*)', result)
    r_code_list = list(r_code)
    if len(r_code_list) > 0:
        code = r_code_list[0].group(1)
        msg = r_code_list[0].group(2)
    r_header = re.finditer('(.*): (.*)', result)
    r_header_list = list(r_header)
    if len(r_header_list) > 0:
        header = {item.group(1): item.group(2) for item in r_header_list}
    return code, msg, content, header


if __name__ == '__main__':
    result1 = socket_client("www.baidu.com", '14.215.177.39')
    # print(result1)
    code1, msg1, content1, header1 = result_format(result1)
    print(f"code:{code1}, msg: {msg1}")
    for key, value in header1.items():
        print(f'{key}: {value}')
    print(f"content: {content1}")

    # print("test2: ")
    # result2 = socket_client("www.sogou.com", '183.36.114.45', param="web?query=ip")
    # print(result2)
